package com.ulook.planetmanager.ui.notifications;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageUtil;
import com.donkingliang.imageselector.utils.UriUtils;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.ulook.planetmanager.R;
import com.ulook.planetmanager.base.BaseFragment;
import com.ulook.planetmanager.common.ActivityCode;
import com.ulook.planetmanager.model.TCommunity;
import com.ulook.planetmanager.util.ThrowException;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import static android.app.Activity.RESULT_OK;

public class NotificationsFragment extends BaseFragment {

    private NotificationsViewModel viewModel;
    private View root;
    private EditText topicNameAddTx;
    private Button chooseCom;
    private Button chooseImg;
    private Button topicAddBt;
    private TextView comName;
    private ImageView imageView;
    private EditText topicNameDelTx;
    private Button topicDelBt;

    private QMUIPopup mNormalPopup;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(this).get(NotificationsViewModel.class);
        root = inflater.inflate(R.layout.fragment_notifications, container, false);

        viewModel.getToastText().observe(getActivity(), s -> {
            Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
        });
        viewModel.getCommunities().observe(getActivity(), tCommunities -> {
            onClickChooseCom(tCommunities);
        });


        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    private void initData(){
        QMUITopBarLayout topBar = root.findViewById(R.id.main_topic_bar);
        topBar.setTitle(R.string.title_notifications);

        topicNameAddTx = root.findViewById(R.id.main_topic_name);
        chooseCom = root.findViewById(R.id.main_topic_comu_bt);
        chooseImg = root.findViewById(R.id.main_topic_img_bt);
        topicAddBt = root.findViewById(R.id.main_topic_pub_bt);
        comName = root.findViewById(R.id.main_topic_comu);
        imageView = root.findViewById(R.id.main_topic_img);
        topicNameDelTx = root.findViewById(R.id.main_topic_delete);
        topicDelBt = root.findViewById(R.id.main_topic_delete_bt);

        // 添加图片
        chooseImg.setOnClickListener(view -> {
            ArrayList<String> images = new ArrayList<>();
            ImageSelector.builder()
                    .useCamera(false) // 设置是否使用拍照
                    .setSingle(false)  //设置是否单选
                    .setMaxSelectCount(1) // 图片的最大选择数量，小于等于0时，不限数量。
                    .setSelected(images) // 把已选的图片传入默认选中。
                    .canPreview(true) //是否可以预览图片，默认为true
                    .start(NotificationsFragment.this, ActivityCode.LOCAL_IMAGE); // 打开相册
        });
        // 选择分组
        chooseCom.setOnClickListener(view -> {
            viewModel.getComList();
        });
        // 添加话题
        topicAddBt.setOnClickListener(view -> {
            String name = topicNameAddTx.getText().toString();
            viewModel.addTopic(name);

        });
        // 删除话题
        topicDelBt.setOnClickListener(view -> {
            String name = topicNameDelTx.getText().toString();
            viewModel.deleteTopic(name);
        });
    }

    /**
     * 选择分组弹窗
     */
    private void onClickChooseCom(List<TCommunity> tCommunities) {
        String[] listItems = new String[tCommunities.size()];
        for(int i = 0; i < tCommunities.size(); i++){
            listItems[i] = new String(tCommunities.get(i).getName());
        }
        List<String> data = new ArrayList<>();
        Collections.addAll(data, listItems);

        ArrayAdapter adapter = new ArrayAdapter<>(getContext(), R.layout.simple_list_item, data);
        AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // 设置选中的Item
                comName.setText(viewModel.getCommunities().getValue().get(i).getName());
                comName.setVisibility(View.VISIBLE);
                viewModel.setComId(viewModel.getCommunities().getValue().get(i).getUid());
                if (mNormalPopup != null) {
                    mNormalPopup.dismiss();
                }
            }
        };
        mNormalPopup = QMUIPopups.listPopup(getContext(),
                QMUIDisplayHelper.dp2px(getContext(), 250),
                QMUIDisplayHelper.dp2px(getContext(), 300),
                adapter,
                onItemClickListener)
                .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                .preferredDirection(QMUIPopup.DIRECTION_TOP)
                .shadow(true)
                .offsetYIfTop(QMUIDisplayHelper.dp2px(getContext(), 5))
                .skinManager(QMUISkinManager.defaultInstance(getContext()))
                .onDismiss(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        //Toast.makeText(getContext(), "onDismiss", Toast.LENGTH_SHORT).show();
                    }
                })
                .show(chooseCom);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            // 设置页面获取权限的结果
            case ActivityCode.PERMISSION_CODE :
                if (resultCode == RESULT_OK) {
                    checkPermission();
                }
                break;
            //获取图片选择器返回的数据
            case ActivityCode.LOCAL_IMAGE :
                if(data != null){
                    ArrayList<String> images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
                    //Log.d("####-image_return", images.toString());
                    displayImages(images.get(0));
                }
                break;
        }
    }

    /**
     * 重命名并展示图片
     */
    private void displayImages(String imgName){
        Uri uri = UriUtils.getImageContentUri(getActivity(), imgName);
        Bitmap bitmap = ImageUtil.getBitmapFromUri(getActivity(), uri);
        String imageName = UUID.randomUUID() + ".jpg";
        // 创建缓存文件
        File imageFile = new File(getActivity().getExternalCacheDir().getPath() + File.separator + imageName);
        try {
            // 写入文件
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imageFile));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            ThrowException.print(e, "图片转化失败");
            return;
        }
        // 展示图片
        imageView.setImageURI(UriUtils.getImageContentUri(getActivity(), imageFile.getPath()));
        viewModel.setImageFile(imageFile);
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), permissions, ActivityCode.PERMISSION_CODE);
                    return;
                }
            }
        }
    }
    /**
     * 权限申请结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == ActivityCode.PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                // 没有权限，主动跳转到权限设置页面
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, ActivityCode.PERMISSION_CODE);
                    return;
                }
            }
        }
    }
}